//
// This is the scripting that drives the application
//
var atlasDoc;
var topLevel;	// flag indicating top of server context
var blogLevel;	// flag indicating top of blog context
var postLevel;	// flag indicating blog post view
var blogName;	// if !topLevel, this is set to the name of the blog
var postName;	// if postLevel, this is the name of the blog post
var username;	// currently logged in user
var roles;		// populated with current role(s)

function setupPage() {
	layoutHeader();
	layoutCenter();
}

function layoutHeader() {
	var headerDiv = document.getElementById("hd");
	if (topLevel==true) {
		headerDiv.innerHTML = "<h2>ScalableType</h2>";
	}
	else {	// blogs always have same header
		YUI().use("io-base", function(Y) {
			function success(id, o) {
				//YUI().use('json-parse', function (Y) {
				try {
					//var blog = Y.JSON.parse("("+o.responseText+")").items[0];
					var blog = eval("("+o.responseText+")").items[0];
					headerDiv.innerHTML = "<h2><a href=\'/"+blogName+"/\'>"+blog.title+"</a><br/>"+blog.slogan+"</h2>";
				} catch (e) {
					alert("Problem parsing json:"+e.name+" "+e.message+
						"\n\n"+o.responseText);
				}
				//});
			}
			function failure(id, o) {
				alert("Error fetching blog entity");
			}

			Y.on('io:success', success, this);
			Y.on('io:failure', failure, this);
			Y.io.header('Accept', 'application/json');

			var request = Y.io(urlLookup("Blog"), { method:'GET' });
			}
		);
	}
}

function layoutCenter() {
	var centerDiv = document.getElementById("center");
	if (topLevel==true) {
		centerDiv.innerHTML = "Consider hosting a blog with us!<p/>";
		centerDiv.innerHTML += "Here are some blogs currently hosted here:<br/>";
		YUI().use("io-base", function(Y) {
			function success(id, o) {
				//YUI().use('json-parse', function (Y) {
				try {
					//var entries = Y.JSON.parse("("+o.responseText+")").items;
					var blogs = eval("("+o.responseText+")").items;
					for (var i=0; i<blogs.length; i++) {
						centerDiv.innerHTML += "<a href='"+blogs[i].name+"/'><span style='fontSize: 24'>"+blogs[i].title+"</span></a><p/>";
					}
				} catch (e) {
					alert("Problem parsing json:"+e.name+" "+e.message+
						"\n\n"+o.responseText);
				}
				//});
			}
			function failure(id, o) {
				alert("Error fetching blog list");
			}

			Y.on('io:success', success, this);
			Y.on('io:failure', failure, this);
			Y.io.header('Accept', 'application/json');

			var request = Y.io(urlLookup("Blog"), { method:'GET' });
			}
		);
	}
	else if (blogLevel==true) {
		centerDiv.innerHTML = "";
		YUI().use("io-base", function(Y) {
			function success(id, o) {
				//YUI().use('json-parse', function (Y) {
				try {
					//var entries = Y.JSON.parse("("+o.responseText+")").items;
					var entries = eval("("+o.responseText+")").items;
					for (var i=0; i<entries.length; i++) {
						centerDiv.innerHTML += "<a href='"+entries[i].name+"/'><span style='fontSize: 24'>"+entries[i].title+"</span></a><br/>";
						centerDiv.innerHTML += "<span style='fontSize: 12'>"+entries[i].date+"</span><p/><p/>";
					}
				} catch (e) {
					alert("Problem parsing json:"+e.name+" "+e.message+
						"\n\n"+o.responseText);
				}
				//});
			}
			function failure(id, o) {
				alert("Error fetching blog entity");
			}

			Y.on('io:success', success, this);
			Y.on('io:failure', failure, this);
			Y.io.header('Accept', 'application/json');

			var request = Y.io(urlLookup("BlogEntry"), { method:'GET' });
			}
		);
	}
	else if (postLevel==true) {
		YUI().use("io-base", function(Y) {
			function success(id, o) {
				//YUI().use('json-parse', function (Y) {
				try {
					//var entries = Y.JSON.parse("("+o.responseText+")").items;
					var entries = eval("("+o.responseText+")").items;
					centerDiv.innerHTML = "<b>"+entries[0].title+"</b><br/>";
					centerDiv.innerHTML += "<span style='fontSize: 12'>"+entries[0].date+"</span><p/><p/>";
					centerDiv.innerHTML += "<div id='blog_body'></div><p/>";
					loadBlogBody("blog_body", "http://storage.scalabletype.org/"+entries[0].s3Key);
					loadMedia(entries[0].id);
				} catch (e) {
					alert("Problem parsing json:"+e.name+" "+e.message+
						"\n\n"+o.responseText);
				}
				//});
			}
			function failure(id, o) {
				alert("Error fetching blog entity");
			}

			Y.on('io:success', success, this);
			Y.on('io:failure', failure, this);
			Y.io.header('Accept', 'application/json');

			var request = Y.io(urlLookup("BlogEntry")+"?name="+postName, { method:'GET' });
			}
		);
	}
}

function loadBlogBody(tagName, url) {
	YUI().use("io-base", function(Y) {
		function success(id, o) {
			var bodyDiv = document.getElementById(tagName);
			bodyDiv.innerHTML = o.responseText;
		}
		function failure(id, o) {
			alert("Error fetching body :"+url+"\n"+id+"\n"+o.status+"\n"+o.statusText);
		}

		Y.on('io:success', success, this);
		Y.on('io:failure', failure, this);

		var request = Y.io(url, { method:'GET' });
		}
	);
}

function loadMedia(entry_id) {
	var centerDiv = document.getElementById("center");
	YUI().use("io-base", function(Y) {
		function success(id, o) {
			try {
				var entries = eval("("+o.responseText+")").items;
				for (var i=0; i<entries.length; i++) {
					if (entries[i].contentType.substr(0, 5) == 'image') {
						centerDiv.innerHTML += "<a href='http://storage.scalabletype.org/"
								+entries[i].s3Key+"'><img width='200' height='200' src='http://storage.scalabletype.org/"
								+entries[i].s3Key+"'/></a><p/>";
					}
					else {
						centerDiv.innerHTML += "<a href='http://storage.scalabletype.org/"
								+entries[i].s3Key+"'>"+entries[i].s3key+"</a><p/>";
					}
				}
			} catch (e) {
				alert("Problem parsing json:"+e.name+" "+e.message+
					"\n\n"+o.responseText);
			}
		}
		function failure(id, o) {
			alert("Error fetching media entities");
		}

		Y.on('io:success', success, this);
		Y.on('io:failure', failure, this);
		Y.io.header('Accept', 'application/json');

		var request = Y.io(urlLookup("Media")+"?entry="+entry_id, { method:'GET' });
		}
	);
}

function urlLookup(name) {
	var apiUrl = "api";
	if (name != null) {
		var apis = atlasDoc.items;
		for (var i=0; i<apis.length; i++) {
			if (apis[i].api == name) {
				apiUrl += "/"+apis[i].href;
				break;
			}
		}
	}
	if (blogLevel==true) apiUrl = "../"+apiUrl;
	else if (postLevel==true) apiUrl = "../../"+apiUrl;
	return apiUrl;
}

function loadAtlas() {
	var fields = new String(document.URL).split('/');
	var info = "Fields found :";
	for (var i=0; i<fields.length; i++) {
		info = info + "\n"+i+" "+fields[i];
	}
//	alert(info);
	if (fields.length > 5) { // !top level
		if (fields.length > 6) { // !blog level
			postLevel = true;
			postName = fields[5];
		}
		else {
			blogLevel = true;
		}
		blogName = fields[4];
	}
	else {
		topLevel = true;
	}
//	alert("top level = "+topLevel+"\nblog level = "+blogLevel+"\npost level = "+postLevel);
	YUI().use("io-base", function(Y) {
		function success(id, o) {
			atlasDoc = eval("("+o.responseText+")");
			username = atlasDoc.user;
			// use these for sanity debug
//			alert("top level = "+topLevel+"\nblog level = "+blogLevel+"\npost level = "+postLevel);
//			alert("blog name = "+blogName+"\npost name = "+postName+"\nuser = "+username+"\nroles = "+roles);
			setupPage();
		}
		function failure(id, o) {
			alert("Error fetching atlas");
		}

		Y.on('io:success', success, this);
		Y.on('io:failure', failure, this);
		Y.io.header('Accept', 'application/json');

		var apiUrl = "api";
		if (blogLevel==true) apiUrl = "../"+apiUrl;
		else if (postLevel==true) apiUrl = "../../"+apiUrl;
		var request = Y.io(apiUrl, { method:'GET' });
		}
	);
}
